/**
 *
 *
 * @author TOTORO
 * @date 2021/6/22 10:08
 */

$(function () {
    // 步骤条点击效果
    $(".next-step-item-node").click(function () {
        $(this).addClass("clicked");
        var that = $(this);
        setTimeout(function () {
            that.removeClass("clicked");
        },100);
    })

    // 地址悬浮事件
    $(".address-list").on({
        mouseenter: function () {
            $(this).addClass("addr-active").siblings().removeClass("addr-active");
        },
        mouseleave: function () {
            $(this).removeClass("addr-active");
        }
    }, ".addr-item-wrapper")

    // 点击地址
    $(".address-list").on("click", ".addr-item-wrapper", function () {
        startLoading();
        var that = $(this);
        setTimeout(function () {
            endLoading();
            that.find(".modify-operation").remove();
            that.siblings().find(".modify-operation").remove();
            that.addClass("addr-active addr-selected").siblings().removeClass("addr-active addr-selected");
            that.find(".inner-infos").append("<a title='修改地址' class='modify-operation'>修改</a>");
        }, 300);

        // 修改底部收货地址
        var addrStr = "";
        that.find(".addr-hd").children(":not(:last)").each(function (index, el) {
            addrStr+=" "+$(this).text();
        });
        addrStr+=" "+that.find(".addr-bd").children(":eq(0)").text();
        addrStr+=" "+that.find(".addr-bd").children(":eq(1)").text();

        var help = that.find(".addr-hd").children(":last-child").text();
        var consignee = help.substring(1, help.length-2)+" ";
        consignee+=that.find(".addr-bd").children(":last-child").text();

        $(".confirmAddr-addr .confirmAddr-addr-bd").text(addrStr);
        $(".confirmAddr-addr-user .confirmAddr-addr-bd").text(consignee);
    })

    // 点击展示更多地址
    $("#showMoreAddress").click(function () {
        $.ajaxSettings.async = false;
        $.post("/productBuy_logic/showMoreAddr.htm", function (data) {
            var addressJson = JSON.parse(data);
            console.log(addressJson);
            for (let i = 0; i < addressJson.length; i++) {
                // 分割地区
                var hds = addressJson[i]['address'].split(" ");

                var addressBox = $("<div class='addr-item-wrapper TwoRow addr-not-default' data-value='"+addressJson[i]['id']+"'>\n" +
                    "<div class='inner-infos'>\n" +
                    "<div class='addr-hd'>\n" +
                    "</div>\n" +
                    "<div class='addr-bd'><span>"+hds[hds.length-1]+"</span><span>"+addressJson[i]['detail']+"</span><span>"+addressJson[i]['phone']+"</span>\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "<div class='set-default' title='设置当前地址为默认'>设为默认</div>\n" +
                    "<div class='default-tip'>默认地址</div>\n" +
                    "<div class='curMarker'></div>\n" +
                    "</div>").appendTo($(".address-list"));

                for (let j = 0; j < hds.length-1; j++) {
                    var hd = $("<span>"+hds[j]+" </span>").appendTo(addressBox.find(".addr-hd"));
                }
                var lxr = $("<span>（"+addressJson[i]['consignee']+"收）</span>").appendTo(addressBox.find(".addr-hd"));
            }
        });
        // 删除显示更多地址标签，换成添加地址
        $(this).remove();
        $("<button type='button' class='next-btn next-medium next-btn-normal operation TwoRow' id='useNewAddress'>使用新地址</button>").appendTo($(".operations"));
    });

    // 点击设为默认
    $(".address-list").on("click", ".set-default", function () {
        // 获取地址id
        var $addr = $(this).parents(".addr-item-wrapper");
        $.post("/user_logic/setAddrDefault.htm", {"addrId": $addr.attr("data-value")}, function (data) {
            var $success = $("<div class='success'>\n" +
                "<i class='iconfont icon-querenzhengque' style='color: #83D24D'></i>设置成功\n" +
                "</div>").appendTo($addr);
            setTimeout(function () {
                $success.remove();
            },1000);
            $addr.removeClass("addr-not-default").addClass("addr-default").siblings().removeClass("addr-default");
        });
    })

    // 点击修改地址，弹出地址框
    $(".address-list").on("click", ".modify-operation", function () {
        // 获取地址id
        var $addr = $(this).parents(".addr-item-wrapper");
        var $addressBox =  generateAddrIframe($addr.attr("data-value")).appendTo("body");
        $addressBox.find(".next-dialog").fadeIn(200);
    });


    // 点击使用新地址，弹出地址框
    $("body").on("click", "#useNewAddress", function () {
        startLoading();
        var $addressBox = generateAddrIframe(0).appendTo("body");
        $addressBox.find(".next-dialog").fadeIn(200);
        setTimeout(endLoading,600);
    });

    // 关闭新增框
    $("body").on("click", "#closeIframe", function () {
        $("body").attr("style", "");
        $(".next-dialog").fadeOut(200);
        setTimeout(function () {
            $(".next-overlay-wrapper").remove();
        }, 300);
    });

    /**
     * 子窗口用来操作该页面的元素
     */
    $("#closeIframeAndRefresh").click(function () {
        // 关闭新增框 | 刷新页面
        $("#addressIframe").remove();
        location.reload();
    });


    // 对某个商品点击减少购买数量
    $(".reduceCount").click(function () {
        var $count = $(this).parent().next().find("input");
        // 获取展示的总价格
        var $rowItemPrice = $(this).parents(".item-row").find(".item-row__price-item").children();
        // 获取展示的单价格
        var $onePrice = $(this).parents(".item-row");

        if($count.val() > 1){
            // 修改数量
            $count.val(parseInt($count.val()) -1);
            // 修改这一行商品的价格
            $rowItemPrice.text(parseFloat($rowItemPrice.text()) - parseFloat($onePrice.attr("data-price")) +".0");
            $(this).removeClass("layui-btn-disabled");
            $(".addCount").removeClass("layui-btn-disabled");
                $(".stock-error").hide();
        } else{
            $(this).addClass("layui-btn-disabled");
            $(".stock-error").text("至少要购买一件").show();
        }
        computeAllPrice();
    });

    // 对某个商品输入购买数量
    $(".pc-input").blur(function () {
        loading(300);
    })

    // 对某个商品点击增加购买数量
    $(".addCount").click(function () {
        var $count = $(this).parent().prev().find("input");
        // 该行商品总数量
        var maxCount = parseInt($(this).parent().parent().children(":eq(0)").val().split(":")[1]);
        // 获取展示的总价格
        var $rowItemPrice = $(this).parents(".item-row").find(".item-row__price-item").children();
        // 获取展示的单价格
        var $onePrice = $(this).parents(".item-row");
        if(parseInt($count.val()) < maxCount) {
            $count.val(parseInt($count.val()) + 1);
            // 修改这一行商品的价格
            $rowItemPrice.text(parseFloat($rowItemPrice.text()) + parseFloat($onePrice.attr("data-price")) +".0");
            $("#reduceCount").removeClass("layui-btn-disabled");
            $(".stock-error").hide();
        } else{
            $(".stock-error").text("最多只能购买"+maxCount+"件").show();
            $(this).addClass("layui-btn-disabled");
        }
        computeAllPrice();
    })

    // 点击修改发票抬头事件
    $(".edit-header").click(function () {
        $(".head-info").addClass("hide");
        $("#change-invoice-head").removeClass("hide");
        var text = $(".head-info").find("span").text();
        $("#personal").val(text);
        $("#personal").focus();
    });

    // 发票抬头输入框取消焦点
    $("#personal").blur(function () {
        $(".head-info").find("span").text($(this).val());
        $(".head-info").removeClass("hide");
        $("#change-invoice-head").addClass("hide");
    });

    // 给卖家留言
    $(".leaveAMessage").focus(function () {
        var $lmTips = $(this).parent().parent().prev();
        $lmTips.find(".remind").remove();
        $(this).css("height","60px");
        $lmTips.append("<span class='remind'>重要提醒</span>");
    }).blur(function () {
        var $lmTips = $(this).parent().parent().prev();
        $(this).attr("style","");
        $lmTips.find(".remind").remove();
    }).keyup(function () {
        var $count = $(this).next().children();
        var nowLen = $(this).val().length;
        $count.text(nowLen+"/200");
    });

    // 重要提醒悬浮事件
    $(".textarea__title").on({
        mouseenter: function () {
            $(".textarea").find(".widget-tips-box").remove();
            $(".textarea").append("<span class='widget-tips-box' style='top: -10px; left: -110px'>\n" +
                "<div class='wtip-msg-box  wtip-msg-right' style='display: block'>\n" +
                "<div class='wtip-arrow-icon'></div>\n" +
                "<ins class='wtip-msg-icon iconfont icon-dengpaotishi'></ins>\n" +
                "<div class=''>此处所填内容仅限对商家的温馨提醒，若您需改变订单内<br/>容或另有特殊需求，请您务必通过旺旺与商家确认一致。<br/>否则，该填写内容将视为无效。</div>\n" +
                "</div>\n" +
                "</span>");
        },
        mouseleave: function () {
            $(".textarea").find(".widget-tips-box").remove();
        }
    },".remind");

});

// 点击立即结算
$(".go-btn").click(function () {
    // 判断卖家是否选择了地址
    if($(".addr-selected").length < 1){
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.alert('<p style="color: #f40">请先选择您的地址 （如果没有可进行添加）</p>', {title: '确认订单', offset: '300px'});
        });
        return false;
    }

    // 如果结算的店铺出现了两个或两个以上，将生成多笔订单，反之
    // 根据店铺进行循环即可 1、获取所有的店铺元素
    var $allShopEl = $(".dinamicx-card-group");
    var scriptObject = new Array();
    for (let i = 0; i < $allShopEl.length; i++) {
        var $product = $allShopEl.eq(i).find(".item-row");
        var pids = new Array();
        var counts = new Array();
        var skuIds = new Array();
        for (let j = 0; j < $product.length; j++) {
            var pid = $product.eq(j).find(".info-detail").attr("data-pid");
            var count = $product.eq(j).find(".order-quantity .next-input-group-auto-width input").val();
            var skuId = $product.eq(j).find(".info-sku").attr("data-sku-id");
            pids.push(pid);
            counts.push(count);
            skuIds.push(skuId);
        }
        var sid = $allShopEl.eq(i).attr("data-sid");
        var arid = $(".addr-selected").attr("data-value");
        var couponId = $allShopEl.eq(i).find(".item-row:first .preferentialType").attr("data-cp-id");
        scriptObject.push({"sid":sid, "arid": arid, "couponId":couponId,"pids":pids,"counts":counts,"skuIds":skuIds});
    }
    var finalData = JSON.stringify(scriptObject);
    // 獲得買家留言
    var buyerMessages = new Array();
    $(".leaveAMessage").each(function (index, el) {
        buyerMessages.push($(this).val().length<1?'无':$(this).val());
    })
    $.post("/order_logic/orderGenerate.htm", {"jsonParam":finalData, "buyerMessages": buyerMessages}, function (msg) {
        if(msg == "time_out_10_min"){
            window.location.href = "/order/confirmOrderError.htm?errorType=TIME_OUT_10_MIN)";
        } else{
            window.location.href = "/order/lightPayCashier.htm?timeStamp="+msg;
        }
    })
})

/**
 * 加载中元素
 */
function startLoading() {
    var $loading =  $("<div class='loading-box' style='position: relative; z-index: 9999;'>\n" +
        "    <img src='//img.alicdn.com/tps/i4/T1YV_TXexaXXbpD82k-184-38.gif' alt='Spinner' style='position: fixed; width: 184px; height: 38px; left: 50%; top: 50%; margin: -19px 0px 0px -92px; z-index: 9999'>\n" +
        "</div>")
    $("body").append($loading);
}

/**
 * 结束加载
 */
function endLoading() {
    $(".loading-box").remove();
}

/**
 * 加载中
 * @param time
 */
function loading(time){
    startLoading();
    setTimeout(function () {
        endLoading();
    }, time)
}

/**
 * 生成地址操作框
 * @param addrId
 * @param url
 * 先隐藏，制造动画效果
 * @returns {*|Window.jQuery|HTMLElement}
 */
function generateAddrIframe(addrId, url) {
    $("body").css({
        "overflow-x":"hidden",
        "overflow-y":"hidden",
        "padding-right":"17px"
    });
    var $iframe =  $("<div class='next-overlay-wrapper opened'>" +
        "<div class=\"next-overlay-backdrop\"></div>" +
        "<div id='addressIframe' class='next-dialog next-closeable next-overlay-inner next-dialog-quick' aria-hidden='false' style='left: 514px; top: 40px; display: none'>\n" +
        "    <div class='next-dialog-header' id='dialog-title-kqyv55sn' role='heading' aria-level='1'>创建地址</div>\n" +
        "    <div class='next-dialog-body' style='max-height: 406px; overflow-y: auto;'>\n" +

        "    </div>\n" +
        "    <a role='button' aria-label='关闭' class='next-dialog-close' id='closeIframe'>\n" +
        "        <i class='next-icon next-icon-close iconfont icon-close' style='font-size: 22px'></i>\n" +
        "    </a>\n" +
        "</div>" +
        "</div>");
    var $url = "/user/receiptAddressIframe.htm?";
    var $param = (addrId==0?"":"addrId="+addrId)+"&spm=_a2_wr_qwv6w_f_rd_zu8cp_i_w_zj9_x_jms_k_g_z_y7_z_d_l0v_p_ec_v_ai_i%252F0_dd0_j_g_u4v_a%253D%253D&from=totoro&reurl=%2F%2Fbuy.totoro.com%2Forder%2FaddressProxy.htm&version=1.0.10&sign_type=TEP&tid=3574779617&id=undefined";

    $("<iframe id='addrIframe' width='850' height='480' src='"+$url+$param+"' scrolling='no'\n" + "frameBorder='0'></iframe>").appendTo($iframe.find(".next-dialog-body"));
    return $iframe;
}


// 优惠券-----------------------
// 获取总共的店铺 （订单商品按店铺来区分）
var $allShop = $(".dinamicx-card-group");
var $nowSelectedShop = jQuery;
for (let i = 0; i < $allShop.length; i++) {

    var couponJson = new Array();
// 获取优惠券
    $.ajaxSettings.async = false;
    var sid = $allShop.eq(i).attr("data-sid");
    var allPrice = $allShop.eq(i).find(".shop-price").val();
    $.post("/productBuy_logic/getCoupon.htm", {"sid":sid, "allPrice":allPrice}, function (data) {
        var f = data.toString().replaceAll("\"", "");
        var final = f.replaceAll("\'", "\"");
        couponJson = JSON.parse(final);
        couponJson.unshift({value:0, label:"不使用优惠", imMy:0, info:"不使用优惠", disabled: false, money:0});
    });
    console.log(couponJson)
    var Main = {
        data() {
            return {
                options: couponJson,
                value: couponJson[0]['label']
            }
        },
        methods: {
            saveDom(value){
                var $that = $(event.currentTarget);
                $nowSelectedShop = $that.parents(".dinamicx-card-group");
            },
            getitemId(value) {
                let obj = {}
                obj = this.options.find(item => {
                    return item.value === value
                });
                $nowSelectedShop.find(".tip-coupon").text(obj.label);
                $nowSelectedShop.find(".preferentialType").text(obj.label).attr("data-cp-id", obj.value);
                $nowSelectedShop.find(".discountedPrice span").text("-"+obj.money);
                // 店铺合计
                var shopPrice = $nowSelectedShop.find(".shop-price").val();
                $nowSelectedShop.find(".shopCountAmout").text("￥"+(shopPrice-obj.money)+".0");
                // 实付款
                $(".realpay--price").text(($(".realpay--price").attr("data-all-price")-obj.money)+".0");
            }
        }
    }
    var Ctor = Vue.extend(Main);
    new Ctor().$mount('#shop-preferential-'+i);

}

function computeAllPrice() {
    $(function () {
        // 获取所有商品

        var $allShop = $(".dinamicx-card-group");
        var allShop = 0;
        for (let i = 0; i < $allShop.length; i++) {
            var $allItem = $allShop.eq(i).find(".item-row");
            var shopPrice = 0;
            for (let j = 0; j < $allItem.length; j++) {
                // 计算该店铺的总价
                var price = $allItem.eq(j).attr("data-price");
                var amout = $allItem.eq(j).find(".pc-input").val();
                console.log(price +"====" +amout);
                shopPrice+=(parseFloat(price) * parseInt(amout));
                console.log("第"+parseInt(i+1)+"次："+price +"*" +amout)
            }
            // 修改该店铺总计
            $allShop.eq(i).find(".shopCountAmout").text("￥"+shopPrice+".0");
            allShop+=shopPrice;
        }
        $(".realpay--price").text(allShop+".0").attr("data-all-price", allShop);
    })

}
